<template>
  <div class="admin-container">
    <div class="admin-header">
      <h1>管理后台</h1>
      <div class="admin-nav">
        <button 
          v-for="tab in tabs" 
          :key="tab.id"
          @click="currentTab = tab.id"
          :class="{ active: currentTab === tab.id }"
          class="nav-btn"
        >
          {{ tab.name }}
        </button>
      </div>
    </div>

    <div class="admin-content">
      <!-- 商品管理 -->
      <div v-if="currentTab === 'products'" class="tab-content">
        <div class="section-header">
          <h2>商品管理</h2>
          <button @click="showProductModal = true" class="add-btn">+ 添加商品</button>
        </div>
        
        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>商品名称</th>
                <th>价格</th>
                <th>库存</th>
                <th>分类</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="product in products" :key="product.id">
                <td>{{ product.id }}</td>
                <td>{{ product.name }}</td>
                <td>¥{{ product.price }}</td>
                <td>{{ product.stock }}</td>
                <td>{{ product.category }}</td>
                <td>
                  <span :class="['status', product.status]">
                    {{ product.status === 'active' ? '上架' : '下架' }}
                  </span>
                </td>
                <td>
                  <button @click="editProduct(product)" class="edit-btn">编辑</button>
                  <button @click="deleteProduct(product.id)" class="delete-btn">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 订单管理 -->
      <div v-if="currentTab === 'orders'" class="tab-content">
        <div class="section-header">
          <h2>订单管理</h2>
        </div>
        
        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>订单号</th>
                <th>用户</th>
                <th>金额</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="order in orders" :key="order.id">
                <td>{{ order.id }}</td>
                <td>{{ order.userName }}</td>
                <td>¥{{ order.total }}</td>
                <td>
                  <span :class="['status', order.status]">
                    {{ getOrderStatusText(order.status) }}
                  </span>
                </td>
                <td>{{ order.createdAt }}</td>
                <td>
                  <select @change="updateOrderStatus(order.id, $event.target.value)" 
                          class="status-select">
                    <option value="pending" :selected="order.status === 'pending'">待处理</option>
                    <option value="paid" :selected="order.status === 'paid'">已支付</option>
                    <option value="shipped" :selected="order.status === 'shipped'">已发货</option>
                    <option value="completed" :selected="order.status === 'completed'">已完成</option>
                  </select>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 用户管理 -->
      <div v-if="currentTab === 'users'" class="tab-content">
        <div class="section-header">
          <h2>用户管理</h2>
        </div>
        
        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>邮箱</th>
                <th>姓名</th>
                <th>角色</th>
                <th>状态</th>
                <th>注册时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.id">
                <td>{{ user.id }}</td>
                <td>{{ user.email }}</td>
                <td>{{ user.name }}</td>
                <td>
                  <select @change="updateUserRole(user.id, $event.target.value)" 
                          class="role-select">
                    <option value="user" :selected="user.role === 'user'">普通用户</option>
                    <option value="admin" :selected="user.role === 'admin'">管理员</option>
                  </select>
                </td>
                <td>
                  <span :class="['status', user.status]">
                    {{ user.status === 'active' ? '活跃' : '禁用' }}
                  </span>
                </td>
                <td>{{ user.createdAt }}</td>
                <td>
                  <button @click="toggleUserStatus(user.id, user.status)" 
                          class="status-btn">
                    {{ user.status === 'active' ? '禁用' : '启用' }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 商品编辑/添加模态框 -->
    <div v-if="showProductModal" class="modal-overlay">
      <div class="modal">
        <h3>{{ editingProduct ? '编辑商品' : '添加商品' }}</h3>
        <form @submit.prevent="saveProduct">
          <div class="form-group">
            <label>商品名称</label>
            <input v-model="productForm.name" required />
          </div>
          <div class="form-group">
            <label>价格</label>
            <input v-model="productForm.price" type="number" required />
          </div>
          <div class="form-group">
            <label>库存</label>
            <input v-model="productForm.stock" type="number" required />
          </div>
          <div class="form-group">
            <label>分类</label>
            <input v-model="productForm.category" required />
          </div>
          <div class="form-group">
            <label>状态</label>
            <select v-model="productForm.status">
              <option value="active">上架</option>
              <option value="inactive">下架</option>
            </select>
          </div>
          <div class="modal-actions">
            <button type="submit" class="save-btn">保存</button>
            <button type="button" @click="showProductModal = false" class="cancel-btn">取消</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useAuthStore } from '../stores/auth'
import { adminService } from '../services/admin'

const authStore = useAuthStore()

const currentTab = ref('products')
const tabs = [
  { id: 'products', name: '商品管理' },
  { id: 'orders', name: '订单管理' },
  { id: 'users', name: '用户管理' }
]

const products = ref([])
const orders = ref([])
const users = ref([])

const showProductModal = ref(false)
const editingProduct = ref(null)
const productForm = reactive({
  name: '',
  price: 0,
  stock: 0,
  category: '',
  status: 'active'
})

const getOrderStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    paid: '已支付',
    shipped: '已发货',
    completed: '已完成'
  }
  return statusMap[status] || status
}

const loadData = async () => {
  try {
    const token = authStore.token
    
    if (currentTab.value === 'products') {
      products.value = await adminService.getProducts(token)
    } else if (currentTab.value === 'orders') {
      orders.value = await adminService.getOrders(token)
    } else if (currentTab.value === 'users') {
      users.value = await adminService.getUsers(token)
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const editProduct = (product) => {
  editingProduct.value = product
  Object.assign(productForm, product)
  showProductModal.value = true
}

const saveProduct = async () => {
  try {
    const token = authStore.token
    
    if (editingProduct.value) {
      await adminService.updateProduct(token, editingProduct.value.id, productForm)
    } else {
      await adminService.createProduct(token, productForm)
    }
    
    showProductModal.value = false
    resetProductForm()
    await loadData()
  } catch (error) {
    console.error('保存商品失败:', error)
  }
}

const deleteProduct = async (productId) => {
  if (confirm('确定要删除这个商品吗？')) {
    try {
      await adminService.deleteProduct(authStore.token, productId)
      await loadData()
    } catch (error) {
      console.error('删除商品失败:', error)
    }
  }
}

const updateOrderStatus = async (orderId, status) => {
  try {
    await adminService.updateOrderStatus(authStore.token, orderId, status)
    await loadData()
  } catch (error) {
    console.error('更新订单状态失败:', error)
  }
}

const updateUserRole = async (userId, role) => {
  try {
    await adminService.updateUserRole(authStore.token, userId, role)
    await loadData()
  } catch (error) {
    console.error('更新用户角色失败:', error)
  }
}

const toggleUserStatus = async (userId, currentStatus) => {
  const newStatus = currentStatus === 'active' ? 'inactive' : 'active'
  try {
    await adminService.updateUserStatus(authStore.token, userId, newStatus)
    await loadData()
  } catch (error) {
    console.error('更新用户状态失败:', error)
  }
}

const resetProductForm = () => {
  Object.assign(productForm, {
    name: '',
    price: 0,
    stock: 0,
    category: '',
    status: 'active'
  })
  editingProduct.value = null
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.admin-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.admin-header {
  margin-bottom: 30px;
}

.admin-header h1 {
  color: #333;
  margin-bottom: 20px;
}

.admin-nav {
  display: flex;
  gap: 10px;
  border-bottom: 2px solid #eee;
}

.nav-btn {
  padding: 10px 20px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-bottom: 3px solid transparent;
  transition: all 0.3s;
}

.nav-btn.active {
  color: #007bff;
  border-bottom-color: #007bff;
}

.nav-btn:hover {
  color: #007bff;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.add-btn {
  padding: 8px 16px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-btn:hover {
  background: #218838;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background: #f8f9fa;
  font-weight: 600;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status.active {
  background: #d4edda;
  color: #155724;
}

.status.inactive {
  background: #f8d7da;
  color: #721c24;
}

.status.pending {
  background: #fff3cd;
  color: #856404;
}

.status.paid {
  background: #d1ecf1;
  color: #0c5460;
}

.status.shipped {
  background: #d4edda;
  color: #155724;
}

.status.completed {
  background: #e2e3e5;
  color: #383d41;
}

.edit-btn, .delete-btn, .status-btn {
  padding: 4px 8px;
  margin: 0 2px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.edit-btn {
  background: #ffc107;
  color: #212529;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.status-btn {
  background: #6c757d;
  color: white;
}

.status-select, .role-select {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 3px;
  font-size: 12px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  padding: 30px;
  border-radius: 8px;
  min-width: 400px;
}

.modal h3 {
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input, .form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.modal-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.save-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn:hover {
  background: #0056b3;
}

.cancel-btn:hover {
  background: #545b62;
}
</style>